package com.baoyouqun.API.IM;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * 腾讯IM UserSig生成工具类（基于HMAC-SHA256加密）
 */
@Component  // 交给Spring管理，便于注入配置
public class UserSigGenerator {

    // 从配置类注入，不再硬编码
    private final long sdkAppId;
    private final String secretKey;

    // 构造方法注入配置
    @Autowired
    public UserSigGenerator(ImConfig imConfig) {
        this.sdkAppId = imConfig.getSdkAppId();
        this.secretKey = imConfig.getSecretKey();
    }

    /**
     * 生成UserSig
     */
    public String generateUserSig(String userId) {
        try {
            long expireTime = 86400; // 有效期：24小时（秒）
            long currentTime = System.currentTimeMillis() / 1000;
            long expire = currentTime + expireTime;

            // 组装待加密的JSON（使用注入的sdkAppId）
            String json = String.format(
                    "{\"TLS.ver\":\"2.0\",\"TLS.identifier\":\"%s\",\"TLS.sdkappid\":%d,\"TLS.expire\":%d,\"TLS.time\":%d}",
                    userId, sdkAppId, expire, currentTime
            );

            // 加密逻辑（使用注入的secretKey）
            SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
            IvParameterSpec iv = new IvParameterSpec(new byte[16]);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);
            byte[] encrypted = cipher.doFinal(json.getBytes());

            return "TLS" + Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            throw new RuntimeException("生成UserSig失败", e);
        }
    }
}